package com.kly.user.serviceImpl.models;

import cn.hutool.system.SystemUtil;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.*;
import com.kly.user.dto.AddModelDto;
import com.kly.user.dto.Model;
import com.kly.user.dto.chatter.Chatter;
import com.kly.user.enums.AlbumsType;
import com.kly.user.service.ModelService;
import com.robert.vesta.util.IdUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service("modelServiceV2")
public class ModelServiceImpl implements ModelService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserProfileDao userProfileDao;

    @Autowired
    private UserInterestsDao userInterestsDao;

    @Autowired
    private InterestDao interestDao;

    @Autowired
    private UserAlbumsDao userAlbumsDao;

    @Autowired
    private UserAlbumsContentDao userAlbumsContentDao;

    @Autowired
    private UserChatterMappingDao userChatterMappingDao;

    @Autowired
    private UserAccountsDao userAccountsDao;


    @Override
    public List<Model> getModels(String queryParams, Page page) {
        List<Model> res = new ArrayList<>();

        Map<String, Object> map = new HashMap<>();
//        if()
        map.put("userTypes", Arrays.asList(2, 3));
        if (StringUtils.isNotEmpty(queryParams)) {
            Any deserialize = JsonIterator.deserialize(queryParams);
            if (deserialize != null) {
                Set<String> keys = deserialize.keys();
                if (keys.contains("nickName")) {
                    String nickName = deserialize.get("nickName").toString();
                    if (StringUtils.isNotEmpty(nickName)) map.put("nickName", nickName);
                }

                if (keys.contains("assignedChatter")) {
                    String assignedChatter = deserialize.get("assignedChatter").toString();
                    if (StringUtils.isNotEmpty(assignedChatter)) map.put("assignedChatter", assignedChatter);
                }

                if (keys.contains("userCode")) {
                    String userCode = deserialize.get("userCode").toString();
                    if (StringUtils.isNotEmpty(userCode)) map.put("userCode", userCode);
                }
            }
        }

        List<UserEntity> userEntities = userDao.queryUsers(map, page);
        List<String> userCodes = userEntities.parallelStream().map(UserEntity::getUserCode).collect(Collectors.toList());
        Map<String, UserChatterMappingEntity> chatterMappingEntityHashMap = new HashMap<>();
        List<UserChatterMappingEntity> userChatterMappingEntities = userChatterMappingDao.queryByModelUserCodes(userCodes);
        userChatterMappingEntities.forEach(userChatterMappingEntity -> {
            chatterMappingEntityHashMap.put(userChatterMappingEntity.getModelUserCode(), userChatterMappingEntity);
        });
        List<UserProfileEntity> aboutMeList = userProfileDao.getList(userCodes, 1);
        Map<String, UserProfileEntity> aboutMeMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(aboutMeList)) {
            aboutMeList.forEach(userProfileEntity -> {
                aboutMeMap.put(userProfileEntity.getUserCode(), userProfileEntity);
            });
        }

        List<UserProfileEntity> targetList = userProfileDao.getList(userCodes, 2);
        Map<String, UserProfileEntity> targetMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(targetList)) {
            targetList.forEach(p -> {
                targetMap.put(p.getUserCode(), p);
            });
        }

        List<UserAlbumsContentEntity> userAlbumsContentEntities = userAlbumsContentDao.queryImagesByAlbumTypes(userCodes, Arrays.asList(AlbumsType.PERSONAL_ALBUMS.getType(), AlbumsType.PRIVATE_ALBUMS.getType(), AlbumsType.PUBLIC_ALBUMS.getType()));
        Map<String, Map<Integer, List<UserAlbumsContentEntity>>> albumsType = new HashMap<>();

        userAlbumsContentEntities.forEach(userAlbumsContentEntity -> {
            Map<Integer, List<UserAlbumsContentEntity>> integerListMap = new HashMap<>();
            if (albumsType.containsKey(userAlbumsContentEntity.getUserCode())) {
                integerListMap = albumsType.get(userAlbumsContentEntity.getUserCode());
            }

            List<UserAlbumsContentEntity> userAlbumsContentEntities1 = new ArrayList<>();
            if (integerListMap.containsKey(userAlbumsContentEntity.getAlbumType())) {
                userAlbumsContentEntities1 = integerListMap.get(userAlbumsContentEntity.getAlbumType());
            }

            userAlbumsContentEntities1.add(userAlbumsContentEntity);
            integerListMap.put(userAlbumsContentEntity.getAlbumType(), userAlbumsContentEntities1);
            albumsType.put(userAlbumsContentEntity.getUserCode(), integerListMap);
        });

        List<UserInterestsEntity> userInterestsEntities = userInterestsDao.queryInterestsByUserCode(userCodes);
        Map<String, List<String>> userCodesAndInterests = new HashMap<>();
        userInterestsEntities.forEach(userInterestsEntity -> {
            List<String> intestsList = new ArrayList<>();
            if (userCodesAndInterests.containsKey(userInterestsEntity.getUserCode())) {
                intestsList = userCodesAndInterests.get(userInterestsEntity.getUserCode());
            }
            intestsList.add(userInterestsEntity.getInterestCode());
            userCodesAndInterests.put(userInterestsEntity.getUserCode(), intestsList);
        });


        userEntities.forEach(u -> {
            Model model = new Model();
            model.setModelCode(u.getUserCode());
            model.setName(u.getNickName());
            model.setOnlineStatus(u.getOnline());
            model.setGender(u.getGender());
            model.setAvatarUrl(u.getAvatarUrl());
            model.setTurnsOnDetail("--");
            model.setStatus(u.getStatus());
            model.setBirthDay(u.getBirthday());
            model.setLookingFor(u.getLookingFor());
            model.setTarget(targetMap.containsKey(u.getUserCode()) ? targetMap.get(u.getUserCode()).getUserProfileType() : 0);
            model.setAboutMe(aboutMeMap.containsKey(u.getUserCode()) ? aboutMeMap.get(u.getUserCode()).getAboutMe() : "");
            model.setLastOnlineTime(u.getOnlineTimestamp() == null ? null : new Date(Long.parseLong(u.getOnlineTimestamp())));
            int hourStart = 0;
            int hourEnd = 0;
            if (u.getOnlineTimeStart() != null) hourStart = DateUtil.getHour(u.getOnlineTimeStart());

            if (u.getOnlineTimeEnd() != null) hourEnd = DateUtil.getHour(u.getOnlineTimeEnd());
            model.setOnlineTime(hourStart + "/" + hourEnd);
            model.setCreateDt(u.getGmtCreate());
            model.setModelType(u.getUserType());
            model.setInterests(userCodesAndInterests.get(u.getUserCode()));

            if (chatterMappingEntityHashMap.containsKey(u.getUserCode())) {
                model.setChatterCode(chatterMappingEntityHashMap.get(u.getUserCode()).getChatterUserCode());
                model.setChatterName(chatterMappingEntityHashMap.get(u.getUserCode()).getChatterNickName());
            }

            if (albumsType.containsKey(u.getUserCode())) {
                if (albumsType.get(u.getUserCode()).containsKey(AlbumsType.PERSONAL_ALBUMS.getType())) {
                    List<String> personalImages = albumsType.get(u.getUserCode()).get(AlbumsType.PERSONAL_ALBUMS.getType()).parallelStream().map(UserAlbumsContentEntity::getImageUrl).collect(Collectors.toList());
                    model.setImages(personalImages);
                }
                if (albumsType.get(u.getUserCode()).containsKey(AlbumsType.PUBLIC_ALBUMS.getType())) {
                    List<String> publicImages = albumsType.get(u.getUserCode()).get(AlbumsType.PUBLIC_ALBUMS.getType()).parallelStream().map(UserAlbumsContentEntity::getImageUrl).collect(Collectors.toList());
                    model.setPublicImages(publicImages);
                }

                if (albumsType.get(u.getUserCode()).containsKey(AlbumsType.PRIVATE_ALBUMS.getType())) {
                    List<String> publicUrls = albumsType.get(u.getUserCode()).get(AlbumsType.PRIVATE_ALBUMS.getType()).parallelStream().map(UserAlbumsContentEntity::getImageUrl).collect(Collectors.toList());
                    model.setPrivateImages(publicUrls);
                }
            }

            res.add(model);
        });


        return res;
    }

    @Override
    public String addNewModel(AddModelDto modelDto) {
        String userCode = IdUtils.genId() + "";
        UserEntity user = new UserEntity().setUserCode(userCode).setOnline(2).setGender(modelDto.getGender()).setStatus(1).setUserType(modelDto.getModelType()).setAvatarUrl(modelDto.getAvatar().replace("https://storage.googleapis.com/meboo-online-b68e7.appspot.com", "")).setLookingFor(modelDto.getLookingFor()).setBirthday(modelDto.getBirthday()).setGpsPrivilege(0).setNickName(modelDto.getNickName()).setCreateAt(new Date()).setRegisterDate(new Date()).setOnlineTimestamp(System.currentTimeMillis() + "").setWorkType(1).setVersion("web");

        userDao.insert(user);

        UserProfileEntity userProfileEntity = new UserProfileEntity();
        userProfileEntity.setUserCode(userCode).setAboutMe(modelDto.getAboutMe()).setUserProfileType(1);
        userProfileDao.insert(userProfileEntity);


        // TODO: 2023/8/26
        Integer whyYouHere = modelDto.getWhyYouHere();
        String target = "";
        if (whyYouHere == 1) {
            target = "Making new friends";
        } else if (whyYouHere == 2) {
            target = "Seeking a long-term partner";
        } else {
            target = "Looking for a dating partner";
        }
        UserProfileEntity userProfileEntity2 = new UserProfileEntity();
        userProfileEntity2.setUserCode(userCode).setAboutMe(target).setUserProfileType(2);
        userProfileDao.insert(userProfileEntity2);

        UserAccountsEntity userAccountsEntity = new UserAccountsEntity().setUserCode(userCode).setAccount(userCode).setAccountType(3).setAccountPassword(userCode).setAccountName(modelDto.getNickName()).setAccountDetail(userCode);
        userAccountsDao.insert(userAccountsEntity);


        addAlbumsContent(userCode, 1, Stream.of(modelDto.getPhotos().toArray(new String[0])).collect(Collectors.toList()));
        addAlbumsContent(userCode, 2, Stream.of(modelDto.getPublicAlbum().toArray(new String[0])).collect(Collectors.toList()));
        addAlbumsContent(userCode, 3, Stream.of(modelDto.getPrivateAlbum().toArray(new String[0])).collect(Collectors.toList()));

        List<InterestEntity> allInterests = interestDao.getAll();
        Map<Integer, InterestEntity> interestEntityMap = new HashMap<>();
        allInterests.forEach(interestEntity -> {
            interestEntityMap.put(interestEntity.getId().intValue(), interestEntity);
        });

        if (CollectionUtils.isNotEmpty(modelDto.getInterests())) {
            modelDto.getInterests().forEach(i -> {
                UserInterestsEntity userInterestsEntity = new UserInterestsEntity().setInterest(interestEntityMap.get(i).getInterestName()).setInterestCode(i + "").setUserCode(userCode);
                userInterestsDao.insert(userInterestsEntity);
            });
        }
        return userCode;
    }


    private void addAlbumsContent(String userCode, Integer albumType, List<String> images) {
        if (CollectionUtils.isEmpty(images)) {
            return;
        }
        String albumCode = IdUtils.genId() + "";
        UserAlbumsEntity userAlbumsPerson = new UserAlbumsEntity().setUserCode(userCode).setAlbumCode(albumCode).setStatus(1).setType(albumType);

        userAlbumsDao.insert(userAlbumsPerson);
        //todo
        if (CollectionUtils.isNotEmpty(images)) {
            images.forEach(image -> {
                String imageCode = IdUtils.genId() + "";
                UserAlbumsContentEntity albumsContentEntity = new UserAlbumsContentEntity().setType(image.contains("vedio") ? 2 : 1).setAlbumCode(albumCode).setStatus(1).setAlbumType(albumType).setImageUrl(image.replace("https://storage.googleapis.com/meboo-online-b68e7.appspot.com", "")).setImageCode(imageCode);
                userAlbumsContentDao.insert(albumsContentEntity);
            });
        }

    }
}
